﻿using System;
using Nancy.Security;
using Nancy.Authentication.Forms;
using Nancy;
using System.Collections.Generic;
using System.Linq;
using NancyOauth2.Domains;

namespace NancyOauth2
{
    internal class UserDatabase: IUserMapper
    {
        internal static IUserIdentity GetUserFromToken(string token)
        {
            string clientId;
            if (string.IsNullOrEmpty(token) || !AuthDomain.AllowToken(token, out clientId))
                return null;

            return new DemoUserIdentity {UserName = clientId};
        }

        public IUserIdentity GetUserFromIdentifier(Guid identifier, NancyContext context)
        {
            IApplicationDomain applicationDomain = new ApplicationDomain();
            var users = applicationDomain.GetUsers().ToList();

            var userRecord = users.FirstOrDefault(u => u.Item3 == identifier);

            return userRecord == null
                       ? null
                       : new DemoUserIdentity { UserName = userRecord.Item1 };
        }

        internal static Guid? ValidateUser(string username, string password)
        {
            IApplicationDomain applicationDomain = new ApplicationDomain();
            var users = applicationDomain.GetUsers().ToList();

            var userRecord = users.FirstOrDefault(u => u.Item1 == username && u.Item2 == password);

            return userRecord?.Item3;
        }
    }
}